//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace ChatGPTAI {

    //% block="初始化gpt API密钥:[API] 模型:[MODEL] 温度:[TEMPERATURE]" blockType="command"
    //% API.shadow="string" API.defl="YOUR_API"
    //% MODEL.shadow="dropdownRound" MODEL.options="MODEL"
    //% TEMPERATURE.shadow="range" TEMPERATURE.params.max=100 TEMPERATURE.params.min=1 TEMPERATURE.defl="30"
    export function initializeChatGPTAI(parameter: any, block: any) {
        let gpt_api = parameter.API.code;
        let model = parameter.MODEL.code;
        let temperature = parameter.TEMPERATURE.code/100;
        Generator.addImport(`import requests\nimport json\nfrom pathlib import Path\nimport base64`);
        Generator.addCode(`
api_key=${gpt_api}
api_url = "https://api.gptsapi.net/v1/chat/completions"
upload_url = "https://api.gptsapi.net/v1/files"
gpt_model = "${model}"
gpt_temperature = ${temperature}
gpt_history = [
    {
        "role": "system", 
        "content": [{
            "type": "text",
            "text": "回答问题的时候尽量精简词语。"
        }]
    }
]

def gpt_chat(query):
    gpt_history.append({
        "role": "user", 
        "content": [{
            "type": "text",
            "text":query
        }]
    })

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": gpt_model,  
        "messages": gpt_history,
        "temperature": gpt_temperature
    }
    
    response = requests.post(api_url, headers=headers, json=data)
    response_json = response.json()

    result = response_json["choices"][0]["message"]["content"]
    gpt_history.append({
        "role": "assistant",
        "content": result
    })
    return result

def gpt_chat_image(image_path):
    base64_image = encode_image(image_path)
    image_content = {
        "type": "image_url",
        "image_url": {
            "url": f"data:image/jpeg;base64,{base64_image}"
        }
    }
    gpt_history.append({
        "role": "user", 
        "content": [image_content]
    })

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def transcribe_audio(file_path):
    url = "https://api.gptsapi.net/v1/audio/transcriptions"
    headers = {
        "Authorization": f"Bearer {api_key}"
    }
    files = {
        'file': (file_path, open(file_path, 'rb')),
        'model': (None, 'whisper-1')
    }
    response = requests.post(url, headers=headers, files=files)
    response_json = response.json()
    return response_json.get("text", "")

def text_to_speech(text, audio_file):
    url = "https://api.gptsapi.net/v1/audio/speech"
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    query = {
        "model": "tts-1",
        "input": text,
        "voice": "alloy",
        "response_format": "mp3",
        "speed": 1
    }
    response = requests.post(url, headers=headers, json=query)
    with open(audio_file, "wb") as f:
        f.write(response.content)
def generate_and_save_image(prompt, filename, size="256x256"):
    url = "https://api.gptsapi.net/v1/images/generations"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "dall-e-2",
        "prompt": prompt,
        "n": 1,
        "size": size
    }
    
    response = requests.post(url, json=payload, headers=headers)
    
    if response.status_code == 200:
        data = response.json()
        image_url = data['data'][0]['url']
    
        image_response = requests.get(image_url)
    
        if image_response.status_code == 200:
            with open(filename, "wb") as f:
                f.write(image_response.content)
            print(f"图像已成功保存为 {filename}")
        else:
            print("下载图像失败:", image_response.status_code)
    else:
        print("请求失败:", response.status_code, response.text)
def append_file_content_to_gpt_system(file_path):
    file_path = Path(file_path)
    if file_path.is_file():
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # 将文件内容附加到gpt_system的content
        gpt_history.append({
            "role": "system",
            "content": [{
                "type": "text",
                "text": content
            }]
        })
    else:
        print(f"文件 {file_path} 不存在或不是一个文件。")
`);

    }

    //% block="添加提示词 [FILE] " blockType="command"
    //% FILE.shadow="string" FILE.defl="prompt.txt"
    export function appendFileContentToGPTSystem(parameter: any, block: any) {
        let filePath = parameter.FILE.code;

        Generator.addCode(`
append_file_content_to_gpt_system(${filePath})
`);
    }

    //% block="发送消息 [MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好，AI"
    export function sendMessage(parameter: any, block: any) {
        let message = parameter.MESSAGE.code;
        Generator.addCode(`gpt_chat(${message})`);
    }

    //% block="上传图片 [image] " blockType="command"
    //% image.shadow="string" image.defl="xxx.png"
    export function sendimage(parameter: any, block: any) {
        let image = parameter.image.code;
        Generator.addCode(`
image_path = Path(${image})
gpt_chat_image(image_path)
`);
    }

    //% block="识别音频文件 [AUDIO_FILE] 并返回文本" blockType="reporter"
    //% AUDIO_FILE.shadow="string" AUDIO_FILE.defl="record.wav"
    export function transcribeAudio(parameter: any, block: any) {
        let audioFile = parameter.AUDIO_FILE.code;
        Generator.addCode(`transcribe_audio(${audioFile})`);
    }
    //% block="将文本 [TEXT] 转换为语音并保存为 [AUDIO_FILE]" blockType="command"
    //% TEXT.shadow="string" TEXT.defl="请输入要转换的文本"
    //% AUDIO_FILE.shadow="string" AUDIO_FILE.defl="output.mp3"
    export function textToSpeech(parameter: any, block: any) {
        let text = parameter.TEXT.code;
        let audioFile = parameter.AUDIO_FILE.code; 
        Generator.addCode(`
text_to_speech(${text}, ${audioFile})
`);
    }

    //% block="生成图像 [PROMPT] 并保存为 [FILENAME] " blockType="command"
    //% PROMPT.shadow="string" PROMPT.defl="A beautiful sunset over the ocean"
    //% FILENAME.shadow="string" FILENAME.defl="sunset.png"
    export function generateAndSaveImage(parameter: any, block: any) {
        let prompt = parameter.PROMPT.code;
        let filename = parameter.FILENAME.code;
        Generator.addCode(`
generate_and_save_image(${prompt}, ${filename})
`);
    }
}
